package com.kwshare.user.controller;

import com.kwshare.common.core.domain.Response;
import com.kwshare.common.core.domain.auth.LoginUser;
import com.kwshare.common.core.domain.user.User;
import com.kwshare.common.core.utils.SecurityUtils;
import com.kwshare.common.core.utils.StringUtils;
import com.kwshare.user.service.IUserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 用户管理
 *
 * @author yangjing
 */
@RestController
public class UserController {

    @Resource
    private IUserService userService;

    /**
     * 根据用户账号查询信息
     * @param username 用户账号
     * @return 用户信息
     */
    @GetMapping("/info/{username}")
    public Response<LoginUser> userInfo(@PathVariable("username") String username){
        User userInfo = userService.getUserByUsername(username);
        if(StringUtils.isNull(userInfo)){
            return Response.fail("用户不存在");
        }
        LoginUser loginUser = new LoginUser();
        loginUser.setUser(userInfo);
        return Response.ok(loginUser);
    }

    /**
     * 获取用户信息
     * @return 用户信息
     */
    @GetMapping("/getInfo")
    public Response<?> getInfo(HttpServletRequest httpServletRequest){
        String username = SecurityUtils.getUsername(httpServletRequest);
        User userInfo = userService.getUserByUsername(username);
        if(StringUtils.isNull(userInfo)){
            return Response.fail("用户不存在");
        }
        LoginUser loginUser = new LoginUser();
        loginUser.setUser(userInfo);
        return Response.ok(loginUser);
    }

    /**
     * 获取用户列表信息
     * @param username 账号
     * @param name 姓名
     * @return
     */
    @GetMapping("/list")
    public Response<?> list(String username,String name){
        return Response.ok(userService.getUserList(username,name));
    }

    /**
     * 添加用户
     * @param user 用户
     * @return 结果
     */
    @PostMapping
    public Response<?> add(HttpServletRequest httpServletRequest,@RequestBody User user){
        int insertUser = userService.insertUser(user, SecurityUtils.getUsername(httpServletRequest));
        return Response.ok(insertUser);
    }

    /**
     * 删除用户
     * @param id 用户id
     * @return 结果
     */
    @DeleteMapping("/{id}")
    public Response<?> remove(@PathVariable Long id){
        int deleteUserById = userService.deleteUserById(id);
        if(deleteUserById == 1){
            return Response.ok();
        }else{
            return Response.fail("删除失败");
        }
    }

    /**
     * 更新用户
     * @param user 用户
     * @return 结果
     */
    @PutMapping
    public Response<?> edit(@RequestBody User user, HttpServletRequest httpServletRequest ){
        int updateUser = userService.updateUser(user, SecurityUtils.getUsername(httpServletRequest));
        if(updateUser == 1){
            return Response.ok();
        }else{
            return Response.fail("更新失败");
        }
    }
}
